package component;

import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.io.support.PropertiesLoaderUtils;

import java.io.IOException;
import java.util.Map;
import java.util.Properties;

public class UserConfigureLoader implements ApplicationContextAware {
    private ApplicationContext applicationContext;

    public <T> T load(Class<T> tClass, String path) throws IOException {
        Properties properties = PropertiesLoaderUtils.loadProperties(applicationContext.getResource(path));
        return toJavaBean(tClass,properties);
    }

    public Properties loadProperties(String path){
        try {
            return PropertiesLoaderUtils.loadProperties(applicationContext.getResource(path));
        } catch (IOException e) {
            return null;
        }
    }

    public static<T> T toJavaBean(Class<T> clazz, Map map) {
        try {
            T newBeanInstance = (T) clazz.newInstance();
            BeanUtils.populate(newBeanInstance, map);
            return newBeanInstance;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
